//
//  MainDataCenterViewController.m
//  ERP
//
//  Created by QA on 16/3/14.
//  Copyright © 2016年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MainDataCenterViewController.h"
#import "GEPushViewControllerHelper.h"
#import "MainDataCenterTableCell.h"

#import "WebViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>

#import "ModuleAuthorityEntity+CoreDataClass.h"
#import "RTSpinKitView.h"
#import "UIView+AssistView.h"
#import "NSDictionary+DataFormat.h"
#import "UINavigationBar+Awesome.h"
#import "UIImage+Color.h"
#import "SYNavigationDropdownMenu.h"

@interface MainDataCenterViewController ()

@property (nonatomic,strong) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray *moduleArray;
@property (nonatomic, strong) NSMutableArray *menuArray;

@end

@implementation MainDataCenterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"数据统计"];
        
        //添加菜单权限获取注册
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMenuAuthorityService:)
                                                     name:GetUserBasicInfoServiceKey object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSelectMenuService:)
                                                     name:GetSelectMenuServiceKey object:nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.menuArray = [NSMutableArray array];
    self.tableView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
    
    //添加进度条
    RTSpinKitView *spinner = [[RTSpinKitView alloc] initWithStyle:RTSpinKitViewStyleFadingCircleAlt];
    spinner.center = CGPointMake(SuperWidth / 2, CGRectGetMidY(self.tableView.frame));
    [spinner startAnimating];
    [self.tableView addSubview:spinner];
    
    //加载权限设置
    [self menuModelViewRelod];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor whiteColor]];
    
    //去除黑色阴影线
    UIImage *image = [UIImage imageWithColor:[UIColor colorWithWhite:0.9 alpha:1] size:CGSizeMake(SuperWidth, 0.5)];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6){
        [self.navigationController.navigationBar setShadowImage:image];
    }
    
    //状态栏字体改变
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColorDispose colorWithHexString:@"#333333"], NSForegroundColorAttributeName,
                                                                     [UIFont systemFontOfSize:18.0], NSFontAttributeName, nil]];
}

- (void)dealloc
{
    //移除菜单权限获取注册
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.navigationController.navigationBar lt_reset];
}

#pragma mark -
#pragma mark - NSNotificationCenter

-(void)updateMenuAuthorityService:(NSNotification *)notification
{
    //获取菜单权限列表
    if ([[notification name] isEqualToString:GetUserBasicInfoServiceKey]){
        [self menuModelViewRelod];
    }
}

#pragma mark -
#pragma mark - NSNotificationCenter

-(void)updateSelectMenuService:(NSNotification *)notification
{
    if(!notification.object) {
        [self menuModelViewRelod];
        [self.tableView reloadData];
        
    } else {
        ModuleAuthorityEntity *entity = notification.object;
        self.moduleArray = @[entity];
        
        [self.menuArray removeAllObjects];
        NSPredicate *menuPredicat = [NSPredicate predicateWithFormat:@"moduleType = %@ and parentId = %@", @2, entity.id];
        NSArray *menuArray = [ModuleAuthorityEntity MR_findAllSortedBy:@"order" ascending:YES withPredicate:menuPredicat];
        [self.menuArray addObject:menuArray];
        [self.tableView reloadData];
    }
}

- (void)menuModelViewRelod
{
    //获取主模块
    NSPredicate *predicateMain = [NSPredicate predicateWithFormat:@"parentId = %@ and moduleType = %@", @0, @2];
    ModuleAuthorityEntity *mainEntity = [ModuleAuthorityEntity MR_findFirstWithPredicate:predicateMain sortedBy:@"order" ascending:YES];
    
    //获取主菜单
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"moduleType = %@ and parentId = %@", @2, mainEntity.id];
    NSArray *moduleArray = [ModuleAuthorityEntity MR_findAllSortedBy:@"order" ascending:YES withPredicate:predicate];
    self.moduleArray = moduleArray;
    
    //获取菜单功能模块
    [self.menuArray removeAllObjects];
    for (ModuleAuthorityEntity *entity in moduleArray) {
        NSPredicate *menuPredicat = [NSPredicate predicateWithFormat:@"moduleType = %@ and parentId = %@", @2, entity.id];
        NSArray *menuArray = [ModuleAuthorityEntity MR_findAllSortedBy:@"order" ascending:YES withPredicate:menuPredicat];
        [self.menuArray addObject:menuArray];
    }
    
    //页面数据配置
    [self.tableView reloadData];
    if(moduleArray.count <= 0){
        self.tableView.backgroundColor = [UIColor whiteColor];
        [self.tableView showPromptViewText:@"暂无模块" rect:CGRectMake(0, 0, SuperWidth, SuperHeight - 128) blcok:nil];
    }
    
    //异常进度条
    NSArray *viewArray = self.tableView.subviews;
    for (id view in viewArray) {
        if ([view isKindOfClass:[RTSpinKitView class]]) {
            RTSpinKitView *mSpinKitView = view;
            [mSpinKitView removeFromSuperview];
        }
    }
}

#pragma mark - Table view data source

//-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
//        [tableView setSeparatorInset:UIEdgeInsetsZero];
//    }
//    
//    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
//        [tableView setLayoutMargins:UIEdgeInsetsZero];
//    }
//    
//    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
//        [cell setLayoutMargins:UIEdgeInsetsZero];
//    }
//}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 34;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.moduleArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = [self.menuArray objectAtIndex:section];
    return array.count;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *keyValue = [NSString stringWithFormat:@"ad-%ld",section];
    MainDataCenterTableCell *cell = [tableView dequeueReusableCellWithIdentifier:keyValue];
    if (!cell) {
        cell = [[MainDataCenterTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue index:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    ModuleAuthorityEntity *entity = [self.moduleArray objectAtIndex:section];
    cell.parentLabel.text = entity.title;
    return cell;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = [self.menuArray objectAtIndex:indexPath.section];
    ModuleAuthorityEntity *entity = [array objectAtIndex:indexPath.row];
    
    NSString *keyValue = [NSString stringWithFormat:@"ad-%ld-%ld",indexPath.section,indexPath.row];
    MainDataCenterTableCell *cell = [tableView dequeueReusableCellWithIdentifier:keyValue];
    if (!cell) {
        cell = [[MainDataCenterTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:keyValue index:1];
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    }
    
    [cell.imageIconView sd_setImageWithURL:[NSURL URLWithString:entity.icon] placeholderImage:[UIImage new]];
    cell.titleLabel.text = entity.title;
    
    if(indexPath.row == [self tableView:tableView numberOfRowsInSection:indexPath.section] - 1)
        cell.lineLabel.hidden = YES;
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 52;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSArray *functionArray = [self.menuArray objectAtIndex:indexPath.section];
    if(indexPath.row >= functionArray.count) return;
    
    NSArray *moduleArray = [self.menuArray objectAtIndex:indexPath.section];
    ModuleAuthorityEntity *entity = [moduleArray objectAtIndex:indexPath.row];
    
    if(entity.codeType.integerValue == 1){
        //网页模式
        WebPushParameterModel *model = [[WebPushParameterModel alloc] init];
        model.URL = entity.webCode;
        model.Title = entity.title;
        model.CodeType = CodeTypeWeb;
        
        WebViewController *viewController = [[WebViewController alloc] initWithPushParameterModel:model];
        [self.navigationController pushViewController:viewController animated:YES];
    } else {
        //原生APP模式
        [GEPushViewControllerHelper pushViewControllerCode:entity.nativeCode navigation:self.navigationController];
    }
}

@end
